package com.older.wptsb.util.interceptor;

import com.older.wptsb.domain.po.RequireRole;
import com.older.wptsb.util.JwtUtil;
import com.older.wptsb.util.UserContext;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class RoleInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是处理方法，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequireRole requireRole = handlerMethod.getMethodAnnotation(RequireRole.class);

        // 如果方法上没有@RequireRole注解，直接放行
        if (requireRole == null) {
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        if (token == null || token.isEmpty()) {
            sendErrorResponse(response, "缺少访问凭证");
            return false;
        }

        // 验证token有效性
        if (!JwtUtil.validateToken(token)) {
            sendErrorResponse(response, "访问凭证无效或已过期");
            return false;
        }

        // 解析token获取用户角色
        Claims claims = JwtUtil.parseToken(token);
        if (claims == null) {
            sendErrorResponse(response, "无法解析访问凭证");
            return false;
        }

        // 获取用户角色
        String userRole = (String) claims.get("role");
        if (userRole == null || userRole.isEmpty()) {
            sendErrorResponse(response, "用户角色信息缺失");
            return false;
        }

        // 检查用户角色是否在允许列表中
        String[] allowedRoles = requireRole.value();
        if (allowedRoles.length > 0) {
            boolean hasPermission = Arrays.stream(allowedRoles)
                    .anyMatch(role -> role.equals(userRole));

            if (!hasPermission) {
                sendErrorResponse(response, "权限不足，需要角色: " + Arrays.toString(allowedRoles));
                return false;
            }
        }
        Long userId = JwtUtil.getUserIdFromToken(token);
        UserContext.setUserId(userId);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除ThreadLocal中的用户ID，避免内存泄漏
        UserContext.clear();
    }
    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException, IOException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"error\":\"" + message + "\"}");
    }
}
